<template>
	<div style="display: flex; height: calc(100vh - 280px);">
		<!-- 左边的卡片列表 -->
		<div class="cardList">
			<div v-for="(item, index) in cardList" :key="index" class="cardView"
					 :class="{ 'card-selected': selectedCardId === item.id }"
					 @click="checkProcedure(item.id)">
				<!--				<div>{{ item.code }}</div>-->
				<div>{{ item.procedureName }}</div>
			</div>
		</div>
		<!-- 右边的标签页 -->
		<div style="width: calc(100% - 300px);">
			<el-tabs v-model="activeTab" @tab-click="handleTabClick" type="border-card" style="height:calc(100vh - 260px)">
				<el-tab-pane label="报工记录" name="report">
					<el-table :data="reportData" border header-cell-class-name="witheTableHeader"
										style="width: 100%;height:calc(100vh - 340px)">
						<el-table-column type="index" label="序号" width="80" align="center" />
						<el-table-column prop="reportWorkRecordNo" label="批次号" align="center" width="250" />
						<el-table-column prop="reportTraceCode" label="追溯码" align="center" min-width="150" />
						<el-table-column prop="count" label="报工数量" align="center" />
						<el-table-column prop="createTime" label="报工时间" align="center" />
						<el-table-column prop="materialOutName" label="产出物料" align="center" show-overflow-tooltip />
						<el-table-column prop="status" label="物料状态" :formatter="statusType" align="center" />
						<el-table-column prop="isRexocation" label="撤销报工" align="center" width="100">
							<template #default="scope">
								<span> {{ scope.row.isRevocation ? '已撤销' : '-' }} </span></template>
						</el-table-column>
					</el-table>
				</el-tab-pane>

				<el-tab-pane label="投料记录" name="feed">
					<el-table :data="feedData" max-height="260px" border header-cell-class-name="witheTableHeader"
										style="width: 100%">
						<el-table-column type="index" label="序号" width="80" align="center" />
						<el-table-column prop="batchNo" label="批次号" align="center" width="250" />
						<el-table-column prop="materialName" label="物料名称" align="center" min-width="200"
														 show-overflow-tooltip />
						<el-table-column prop="materialCount" label="投料数量" align="center" />
						<el-table-column prop="createTime" label="投料时间" align="center" min-width="120" show-overflow-tooltip />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="线边库存明细" name="lineInventory">
					<el-table
						:data="lineInventoryData"
						height="calc(100vh - 350px)"
						row-key="id"
						stripe="false"
						header-cell-class-name="witheTableHeader"
					>
						<el-table-column type="index" label="序号" width="80" align="center" />
						<el-table-column label="批次号" prop="batchNo" min-width="150" show-overflow-tooltip align="center" />
						<el-table-column label="物料名称" prop="materialName" min-width="200" show-overflow-tooltip align="center" />
						<el-table-column label="物料编号" prop="materialNo" min-width="200" show-overflow-tooltip align="center" />
						<el-table-column label="数量" prop="count" min-width="150" show-overflow-tooltip align="center" />
						<el-table-column label="物料状态" prop="materialStatus" align="center" min-width="80"
														 :formatter="formatStatus" />
						<el-table-column label="库位名称" prop="storageName" min-width="200" show-overflow-tooltip align="center" />
						<el-table-column label="创建时间" prop="createTime" min-width="150" show-overflow-tooltip align="center" />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="质检记录" name="quality">
					<el-table class="pageTableClass" :data="qualityData" border height="calc(100vh - 320px)" style="width: 100%"
										header-cell-class-name="witheTableHeader">
						<el-table-column label="序号" align="center" width="70" type="index" />
						<el-table-column prop="no" label="单号" align="center" min-width="200" />
						<el-table-column prop="sourceNo" label="来源单号" align="center" min-width="200" />
						<el-table-column prop="qualityType" label="质检类型" align="center" min-width="200">
							<template #default="scope">
								<span> {{ getQualityTypeByValue(scope.row.qualityType) }} </span></template>
						</el-table-column>
						<el-table-column prop="passRate" label="合格率" align="center" min-width="100">
							<template #default="scope">
								<div v-if="scope.row.passRate"> {{ scope.row.passRate }} %</div>
							</template>
						</el-table-column>
						<el-table-column prop="totalQuantity" label="质检数量" align="center" min-width="110" />
						<el-table-column prop="schemeTaskForm.qualifiedQuantity" label="合格数" align="center" min-width="100" />
						<el-table-column prop="schemeTaskForm.unQualifiedQuantity" label="不合格数" align="center"
														 min-width="100" />
						<el-table-column prop="createTime" label="创建时间" align="center" min-width="200" />
					</el-table>
				</el-tab-pane>
				<el-tab-pane label="转码记录" name="coding">
					<el-table :data="codingData" height="calc(100vh - 320px)" border row-key="id" stripe="false"
										header-cell-class-name="witheTableHeader">
						<el-table-column label="序号" align="center" width="55" type="index" />
						<el-table-column label="批次号" prop="batchNo" min-width="200" show-overflow-tooltip align="center" />
						<el-table-column label="物料名称" prop="materialName" min-width="200" show-overflow-tooltip align="center" />
						<el-table-column label="物料编码" prop="materialNo" min-width="200" show-overflow-tooltip align="center" />
						<el-table-column label="数量" prop="count" min-width="150" show-overflow-tooltip align="center" />
						<el-table-column label="单位" prop="basicUnit" min-width="150" show-overflow-tooltip align="center" />
						<el-table-column label="物料状态" prop="materialStatus" align="center" min-width="100"
														 :formatter="formatStatus" />
						<el-table-column label="加工属性" prop="processingStatus" align="center" min-width="100"
														 :formatter="formatProcessingAttributes" />
						<el-table-column label="批次" prop="batch" min-width="150" show-overflow-tooltip align="center" />
						<el-table-column label="库位名称" prop="storageName" min-width="200" show-overflow-tooltip align="center" />
						<el-table-column label="追溯码" prop="traceabilityCode" min-width="250" show-overflow-tooltip align="center" />
						<el-table-column label="转码前追溯码" prop="preorderTraceCode" min-width="250" show-overflow-tooltip
														 align="center" />
						<el-table-column label="创建时间" prop="createTime" min-width="200" show-overflow-tooltip align="center" />
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { ElTabs, ElTabPane, ElTable, ElMessage } from 'element-plus';
import axiosInstance from '@/utils/http/api';

// 响应式变量，用于控制当前激活的标签页
const activeTab = ref('report');

// 左边的卡片列表假数据
const cardList = ref([]);

// 各个标签页的表格假数据
const reportData = ref([]);
const feedData = ref([]);
const lineInventoryData = ref([]);
const qualityData = ref([]);
const codingData = ref([]);
const selectedCardId = ref('1');
const formatStatus = (row, column, cellValue) => {
	switch (cellValue) {
		case 0:
			return '不可用';
		case 1:
			return '可用';
		case 2:
			return '运输中';
		case 3:
			return '生产锁定';
	}
};
// 各个标签页的数据
const props = defineProps({
	preorderTraceCodeList: Array,
	productId: String
});


watch(
	() => props.preorderTraceCodeList,
	(newValue, oldValue) => {
		console.log(oldValue);
		if (newValue !== oldValue) {
			// 当 preorderTraceCodeList 发生变化时，执行 getList 请求
			getList();
		}
	}
);

const getList = () => {
  reportData.value = []
  feedData.value = []
  lineInventoryData.value = []
  qualityData.value = []
	axiosInstance.post('/api/traceCode/procedure/findByTraceCode', {
		preorderTraceCodeList: props.preorderTraceCodeList,
		productId: props.productId
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}

      const processedList =  res.data.reduce((acc, current) => {
        const existingItem = acc.find(item => item.procedureName === current.procedureName);
        if (existingItem) {
          // 如果已存在相同name的项，将id合并为数组
          existingItem.id = Array.isArray(existingItem.id)
              ? [...existingItem.id, current.id]
              : [existingItem.id, current.id];
        } else {
          // 如果不存在，添加新项（id保持为数组形式）
          acc.push({
            ...current,
            id: [current.id]
          });
        }
        return acc;
      }, []);

      cardList.value = processedList;

// 示例结果
      console.log(processedList);
		});
};

const checkProcedure = (cardId) => {
	selectedCardId.value = cardId;

	// 报工记录
	axiosInstance.post('/api/traceCode/procedure/reportWorkRecord/findByTraceCode', {
		procedureIds: cardId,
		preorderTraceCodeList: props.preorderTraceCodeList
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			reportData.value = res.data;
		});

	// 投料记录
	axiosInstance.post('/api/traceCode/procedure/inputStock/findByTraceCode', {
    procedureIds: cardId,
		preorderTraceCodeList: props.preorderTraceCodeList
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			feedData.value = res.data;
		});


	// 线边库存明细
	axiosInstance.post('/api/traceCode/procedure/stock/findByTraceCode', {
    procedureIds: cardId,
		preorderTraceCodeList: props.preorderTraceCodeList
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			lineInventoryData.value = res.data;
		});

	// 质检记录
	axiosInstance.post('/api/traceCode/procedure/qualitySchemeTask/findByTraceCode', {
    procedureIds: cardId,
		preorderTraceCodeList: props.preorderTraceCodeList
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			qualityData.value = res.data;
		});


};


// 处理标签页点击事件
const handleTabClick = (tab) => {
	console.log('当前激活的标签页:', tab.props.name);
};


const getQualityTypeByValue = (e) => {
	let name = null;
	for (const item of qualityTypeList.value) {
		if (e == item.value) {
			name = item.label;
		}
	}
	return name;
};

const qualityTypeList = ref([
	{
		label: '首件检',
		value: '1',
		type: 'material'
	},
	{
		label: '末件检',
		value: '2',
		type: 'material'
	},
	{
		label: '生产',
		value: '3',
		type: 'material'
	},
	{
		label: '巡检',
		value: '4',
		type: 'material'
	},
	{
		label: '入库检',
		value: '5',
		type: 'procedure'
	},
	{
		label: '出库检',
		value: '6',
		type: 'procedure'
	},
	{
		label: '来料检',
		value: '7',
		type: 'procedure'
	}
	// 继续添加更多检查类型...
]);

const statusType = (e) => {
	const list = [{
		label: '不合格',
		value: '0'
	}, {
		label: '合格',
		value: '1'
	}, {
		label: '报废',
		value: '2'
	}];
	const type = list.find(type => type.value == e.status);
	return type ? type.label : '';
};
</script>

<style scoped>
.cardView {
	margin-bottom: 10px;
	height: 80px;
	width: 100%;
	border-radius: 10px;
	border: 1px solid #cdcdcd;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	cursor: pointer;
}

.cardList {
	width: 300px;
	height: 100%;
	overflow-y: auto;
	border-right: 1px solid #e4e7ed;
	padding-right: 10px;
}

.cardView.card-selected {
	background-color: #f0f0f0; /* 选中状态的背景色 */
	border-color: #409eff; /* 选中状态的边框色 */
}
</style>
